import { TreeItem } from '@ide/types/tree';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { Tree } from 'tea-component/lib/tree/Tree';
import { Icon } from 'tea-component/lib/icon/Icon';
import { Popover } from 'tea-component/lib/popover/Popover';
import { DropdownBox } from 'tea-component/lib/dropdown/Dropdown';
import { List } from 'tea-component/lib/list/List';
import { Modal } from 'tea-component/lib/modal/Modal';
import { message } from 'tea-component';
import { downlaodFileByPath, getContractNameByPath, getParentPathByPath } from '@ide/utils/tools';
import useAppStore from '@ide/store';
import { useIdeStore } from 'ide-plugin';
import { exportFile, filesWs, removeFile } from '@/api';
import { versionConfig } from '@/config';
// import { useAppOpenEditor } from '@/hooks/useAppOpenEditor';

function TreePopover({ item, creareContract }: { item: TreeItem, creareContract: string }) {
  const [visible, setVisible] = useState(false);
  const { setting, getFiles, setAddFileInfo, setModalStatus, setNewContractVisible, newnewContractVisible } = useAppStore();
  const { removeEditor, openEditor } = useIdeStore();
  // const {appOpenEditor} = useAppOpenEditor();
  const changeVisible = useCallback((isVisible:boolean) => {
    if (item.editable) {
      setVisible(isVisible);
    }
  }, [item, setVisible]);
  const isWorkspace = useMemo(() => {
    return item.name === 'Workspace' && item.isParent === false && item.type === 'folder';
  }, [item]);
  const removeFileAction = useCallback(async () => {
    if (!item.path) {
      return;
    }
    const yes = await Modal.confirm({
      caption: '二次确认提示',
      message:'',
      description: '请再次确认是否删除该合约文件，删除后将无法恢复',
      okText: '删除',
      cancelText: '取消',
      className: `${setting.theme}_model`,
      maskStyle: {
        backgroundColor: 'rgba(0,0,0,0.2)'
      }
    });
    if (yes) {
      removeFile({ path: item.path }).then(() => {
        getFiles();
        removeEditor(item.path);
      }).catch(e => {
        message.error({ content: e.message });
      });
    }
  }, []);
  const openFile = useCallback(() => {
    if (item.type === 'file') {
      event?.preventDefault();
      const type = item.path.match(/[^.]+$/)?.[0];
      if (type === 'go' || type === 'mod' || type === 'sum' || type === 'js' || type === 'ts' || type === 'sol') {
        openEditor({
          path: item.path,
          name: item.name,
          editable: item.editable
        });
      } else {
        setModalStatus({
          modalShow: true,
          modalContent: '不支持该类型文件'
        });
      }
    }
  }, []);
  const export7Z = useCallback(async () => {
    if (!item.path) {
      return;
    }
    const res = await exportFile({ path: item.path });
    if (res) {
      // const path = await server?.getDownloadPath?.(item.path);
      // if (path) {
      //   window.location.href = path;
      // }
      downlaodFileByPath(`${versionConfig.serverHost}file/7z?path=${res.data}`);
    }
  }, []);
  useEffect(() => {
    if (newnewContractVisible) {
      setNewContractVisible(true);
      setVisible(false);
    }
  }, [newnewContractVisible]);
  return <Popover
    visible={visible}
    onVisibleChange={changeVisible}
    placement="bottom-start"
    trigger="contextMenu"
    overlayClassName={`${setting.theme}_popover`}
    overlay={
      <DropdownBox>
        <List type="option" className="popover-list">
          {!isWorkspace || <>
            <List.Item
              onClick={(e) => {
                e.stopPropagation();
                setNewContractVisible(true);
                setVisible(false);
              }}
            >
             创建合约工程
            </List.Item>
            <List.Item
              onClick={(e) => {
                e.stopPropagation();
                getFiles();
                setVisible(false);
              }}
            >
                刷新
            </List.Item>
          </>}
          {isWorkspace || <>
            {item.type === 'file' || <List.Item
              onClick={(e) => {
                e.stopPropagation();
                setAddFileInfo({
                  isOpenAddFile: true,
                  newFilePath: item.path,
                  newFileName: '.go',
                  addFileType: 'file'
                });
                setVisible(false);
              }}
            >
            创建文件
            </List.Item>}
            {item.type === 'file' || <List.Item
              onClick={(e) => {
                e.stopPropagation();
                setAddFileInfo({
                  isOpenAddFile: true,
                  newFilePath: item.path,
                  newFileName: item.name,
                  addFileType: 'folder'
                });
                setVisible(false);
              }}
            >
            创建文件夹
            </List.Item>}
            <List.Item
              onClick={(e) => {
                e.stopPropagation();
                openFile();
                setVisible(false);
              }}
            >
            打开
            </List.Item>
            <List.Item
              onClick={(e) => {
                e.stopPropagation();
                removeFileAction();
                setVisible(false);
              }}
            >
            删除
            </List.Item>
            {item.canNotRenameAble || <List.Item
              onClick={(e) => {
                e.stopPropagation();
                setAddFileInfo({
                  isOpenAddFile: true,
                  newFilePath: item.path,
                  newFileName: item.name,
                  addFileType: 'rename'
                });
                setVisible(false);
              }}
            >
            重命名
            </List.Item>
            }
            {/* <li className='line-space'></li>
          <List.Item
            onClick={(e) => {
              e.stopPropagation()
              setVisible(false)
            }}
          >
            刷新
          </List.Item> */}
            <li className='line-space'></li>
            <List.Item
              onClick={(e) => {
                e.stopPropagation();
                export7Z();
                setVisible(false);
              }}
            >
            导出
            </List.Item></>}
        </List>
      </ DropdownBox>
    }
  >
    <span onDoubleClick={openFile}>{item.name}</span>
  </Popover>;
}

function drawTree(tree: TreeItem[], creareContract: string): { tree: TreeItem[], expendIds: string[], creareContract: string } {
  const expendIds: string[] = [];
  function format(tree: TreeItem[]): TreeItem[] {
    return tree.map(item => {
      const { type, children, id } = item;
      console.log(item, 'item')
      if (type === 'file') {
        expendIds.push(id);
      }
      return {
        ...item,
        content: <TreePopover item={item} creareContract={creareContract} />,
        icon: type === 'file'
          ? <Icon type="daily" />
          : ({ expanded }: { expanded: boolean }) => {
            return <Icon type={expanded ? 'folderopen' : 'folderclose'} />;
          },
        children: children ? format(children) : undefined
      };
    });
  }
  const newTree = format(tree);
  return { tree: newTree, expendIds, creareContract };
}

let filesWsListener:any;
export default function FileTree({ style, creareContract  }: {
  style?: React.CSSProperties, creareContract: string;
}) {
  let { getFiles, fileTree, userId, expandedIds, setExpandedIds, setActiveTreeNode, getGoModuleFiles, activeTreeNode, contactExpandedIds } = useAppStore();
 
  const { updateEditor, removeEditor, currentFileTab } = useIdeStore();
  console.log(creareContract, 'filetree')
  const totalTree = useMemo(() => {
    // console.log('totalTree')
    return fileTree ? drawTree(fileTree, creareContract).tree : [];
  }, [fileTree, creareContract]);
  const expendChange = useCallback((expends: string[]) => {
    // localStorage.setItem(`${userId}_expends`, JSON.stringify(expends));
    setExpandedIds(expends);
  }, [userId]);
  const changeActiveNode = useCallback((activeIds: any, context: any) => {
    const { path, name } = context.data;
    setActiveTreeNode({ path, name });
  }, []);
  /**
   * 树活动节点自动追踪编辑tab选项
   */
  useEffect(() => {
    if (!currentFileTab?.path) {
      return;
    }
    const currentContractName = getContractNameByPath(currentFileTab.path);
    if(currentContractName){
      getGoModuleFiles(currentContractName);
    }
    setActiveTreeNode({
      path: currentFileTab.path
    });
    contactExpandedIds(getParentPathByPath(currentFileTab.path))
    // console.log(getParentPathByPath(currentFileTab.path));

  }, [currentFileTab]);
  const getFileMsg = useCallback((info: any) => {
    const data = JSON.parse(info?.data);
    switch (data.cmd) {
      case 'update-file':
        // 更新已经打开的文件内容
        updateEditor(data.path, {
          action: {
            type: 'updateCode'
          }
        });
        break;
      case 'create-file':
        getFiles();
        break;
      case 'remove-file':
        getFiles();
        removeEditor(data.path);
        break;
      case 'rename-file':
        getFiles();
        if (data.newPath) {
          updateEditor(data.path, {
            path: data.newPath
          });
        }
        break;
      default:
        break;
    }
  }, []);
  useEffect(() => {
    getFiles();
    filesWsListener = filesWs({});
    filesWsListener.addEventListener('message', getFileMsg);
    return () => {
      filesWsListener.close();
    };
  }, [getFileMsg]);
  return <Tree
      style={style}
      className="file_tree"
      activable
      fullExpandable
      activeIds={[activeTreeNode?.path || '']}
      defaultExpandParent={false}
      expandedIds={expandedIds}
      onActive={changeActiveNode}
      data={totalTree}
      onExpand={expendChange}
    />;
}
